package com.zhuhjay.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import static com.zhuhjay.constant.RedisConstant.ID_WORKER_PREFIX;
import static com.zhuhjay.utils.SpringContextHolder.getBean;

/**
 * id生成器
 * @author ZhuHJay
 * @date 2023/2/2 12:26
 */
public class RedisIdWorker {

    private static final StringRedisTemplate REDIS_TEMPLATE;
    /** 时间戳开始时间 **/
    private static final long BEGIN_TIME;
    /** 偏移量 **/
    private static final long COUNT_BITS = 32L;

    static {
        REDIS_TEMPLATE = getBean(StringRedisTemplate.class);
        LocalDateTime localDateTime = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        BEGIN_TIME = localDateTime.toEpochSecond(ZoneOffset.UTC);
    }

    /**
     * 获取唯一id
     * @param businessKey 业务标识
     * @return id
     */
    @SuppressWarnings("all")
    public static long nextId(String businessKey) {
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 计算时间戳
        long timestamp = nowSecond - BEGIN_TIME;
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // key自增
        long count = REDIS_TEMPLATE.opsForValue().increment(
                ID_WORKER_PREFIX + businessKey + ":" + format);
        return timestamp << COUNT_BITS | count;
    }
}
